var callback_parameters = '';
var start_upload;
var upload_progress;
var upload_finished;
var oss_object_name_prefix = 'prefix_';
//var oss_object_max_size = 1;
// 设置回调信息

var uploadingfileCnt = 0; // 整在上传的文件个数
/**
 * 是否有文件还在上传中
 * @returns
 */
function isUploading() {
	if(uploadingfileCnt <= 0)
		return false;
	else
		return true;
}

/**
 * parameters 回调服务器的参数
 * _start_upload 开始上传
 * _upload_progress 上传过程中的自定义方法
 * _upload_finished 上传结束后的自定义方法
 * _oss_object_max_size 上传文件size上限
 */
function custom_initialize(_oss_object_name_prefix, _start_upload, _upload_progress, _upload_finished, _callback_parameters) {
	oss_object_name_prefix = _oss_object_name_prefix;
	callback_parameters = _callback_parameters;
	start_upload = _start_upload;
	upload_progress = _upload_progress;
	upload_finished = _upload_finished;
	//oss_object_max_size = _oss_object_max_size;
}

accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
user_dir = ''
expire = 0
g_object_name = ''
//g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000; 

function send_request()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  
    if (xmlhttp!=null)
    {
        serverUrl = '../putObject2AliCloudOss.do';
        if(callback_parameters.length > 0)
        	serverUrl += "?queryString=" + callback_parameters;
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
};

function get_signature()
{
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    now = timestamp = Date.parse(new Date()) / 1000; 
    if (expire < now + 3)
    {
        body = send_request();
        var obj = eval ("(" + body + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback'] 
        user_dir = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
	len = len || 32;
	var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
	var maxPos = chars.length;
	var pwd = '';
	for (i = 0; i < len; i++) {
		pwd += chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(fileObj)
{
	filename = fileObj.name; //原名
	if (filename != '') suffix = get_suffix(filename);
	
	filename = oss_object_name_prefix + random_string(10) + suffix;
    g_object_name = user_dir + '/' + filename;
    fileObj.name = g_object_name;
}

function get_uploaded_object_name()
{
    return g_object_name
}

function set_upload_param(up, _g_object_name)
{
    new_multipart_params = {
        'key' : _g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'callback' : callbackbody,
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    //up.start();
}

/**
 * 主动调用初始化方法
 * 初始时图片上传按钮不显示的场合使用（btn的id需要事先存在，本例中btn的id初始时不存在所以需要动态调用）
 */
var uploader;
function ossImgUploadInit(fileId) {
	// 多文件上传or单文件上传
	if("undefined" == typeof multi_selection) {
		multi_selection = true;
	}
	if(multi_selection != false)
		multi_selection = true;

	// 上传对象只生成一次
	if(uploader != null) return;
	uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight,html4',
		//上传文件按钮
		browse_button : 'upload-btn', 
	    multi_selection: multi_selection,
		flash_swf_url : 'js/Moxie.swf',
		silverlight_xap_url : 'js/Moxie.xap',
	    url : 'http://oss.aliyuncs.com',
	    filters : {
	    	max_file_size : '10mb' //最大只能上传10mb的文件
	        ,mime_types : [ //只允许上传图片和zip文件
	        { title : "Image files", extensions : "jpeg,jpg,gif,png,bmp,tiff" },
	        { title : "PDF files", extensions : "pdf,doc,xls,docx,xlsx" }
	        ]
	        ,prevent_duplicates : true //不允许选取重复文件
	    },

	    init: {
			PostInit: function() {
			},

			FilesAdded: function(up, files) {
				plupload.each(files, function(file) {
					start_upload(file);
					uploadingfileCnt++;//上传中计数
				});
				get_signature();
				//set_upload_param(up, user_dir);
				up.start();
			},

			BeforeUpload: function(up, file) {
				calculate_object_name(file)
				set_upload_param(up, get_uploaded_object_name());
	        },

			UploadProgress: function(up, file) {
				upload_progress(file);
			},

			FileUploaded: function(up, file, info) {
	            if (info.status == 200)
	            {
	            	var responseInfo = JSON.parse(info.response);
	            	upload_finished(file, responseInfo);
	            }
	            else if (info.status == 203)
	            {
	            }
	            else
	            {
	            	//alert(info.response);
	            }
	            uploadingfileCnt--;//上传中计数
			},

			Error: function(up, err) {
				
				$('.'+fileId).remove();
	            if (err.code == -600) {
	            	alert("\n选择的文件太大了,请上传小于10m的文件。");
	            }
	            else if (err.code == -601) {
	            	alert("\n选择的文件后缀不对,请上传jpng,jpg,gif,png,bmp文件类型。");
	            }
	            else if (err.code == -602) {
	            	alert("\n这个文件已经上传过一遍了");
	            }
	            else 
	            {
	            	alert("操作失败，请重新上传。");
	            }
	            uploadingfileCnt--;//上传中计数
			}
		}
	});

	uploader.init();
	uploadingfileCnt = 0//初始化
}